import socket
from urllib import request, parse, error


# 普通的网络请求
def urlrequest():
    response = request.urlopen("https://www.baidu.com")
    htmlStr = response.read().decode('utf-8')
    print(htmlStr)
    print(type(response))
    print(response.status)
    print(response.getheaders())
    print(response.getheader("server"))


# 带参数上传
def request_with_param():
    param = {'username': 'test', 'password': '123456'}
    data = bytes(parse.urlencode(param), encoding='utf-8')
    response = request.urlopen("http://image.qystudio.com/api/auth/login.html", data=data)
    print(response.read())


# 网络请求error判断
def request_with_error():
    try:
        response = request.urlopen('http://image.qystudio.com/api/auth/login.html', timeout=0.1)
    except error.URLError as e:
        print('error')
        if isinstance(e.reason, socket.timeout):
            print('time out')


# 使用Request发起网络请求，并带参数
def request_data():
    url = 'http://image.qystudio.com/api/works/index.html'
    headers = {
        'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2NzU3NzQyNDMsImV4cCI6MTY3NTg2MDY0MywianRpIjoiMGQzMTg2NjNjMDJlM2ZjN2NkZjYzZTE4MDY5YWM1ODM3ZGZkZmU2YSIsInVpZCI6OH0.4f3lUIBaDvNE36E8665v3OcpGiHCEDOwnAAOzjmdo1k'
    }
    dict = {
        'page': 1,
        'limit': 20
    }
    data = bytes(parse.urlencode(dict), encoding='utf-8')
    req = request.Request(url=url, data=data, headers=headers, method='POST')
    response = request.urlopen(req)
    print(response.read().decode('utf-8'))


# 解析链接地址
def request_urlparse():
    urlStr = "https://cn.bing.com/search?q=%E4%B8%8A%E5%8F%A4%E5%8D%B7%E8%BD%B4ol&cvid=e3ccf6519545413abc0bb4f5ea92bd0c&gs_lcrp=EgZjaHJvbWUqBggBEAAYQDIGCAAQRRg9MgYIARAAGEAyBggCEAAYQDIGCAMQABhAMgYIBBAAGEAyBggFEAAYQDIGCAYQABhAMgYIBxAAGEAyBggIEAAYQNIBCDUyMDVqMGo0qAIAsAIA&FORM=ANAB01&PC=U531"
    result = parse.urlparse(urlStr)
    print(result)
